const authorization = require('../utils/authorization');
const answers = require('../data/answers')
const getNewData = require('../utils/getNews')

const onEvents = {
  async authenticate(socket,{token}){
    console.log('token-----',token);
    const userInfo = await authorization(token);
    if(userInfo.status && userInfo.status === 200){
      socket.emit('connected',{
        code: 200,
        msg: '用户链接成功',
        userinfo: userInfo.body,
        questionList: answers.data
      })
    } else {
      socket.emit('connected',{
        code: 401,
        msg: '用户鉴权失败,请重新登录'
      })
      onEvents.close(socket);
    }
  },
  close(socket){
    socket.disconnect(true);
    console.log('断开链接');
  },
  async message(socket,{type,id,value}){
    if(type === 'talk'){  // 人工
      const questionId = answers.data.find(({question}) => question.includes(value));
      console.log(questionId);
      socket.emit('message', {
        code:'200',
        data:questionId ? await onEvents.findAnswers(socket,questionId.id) : '暂未开通该功能'
      })
    } else {
      await onEvents.findAnswers(socket,id);
    }
  },
  async findAnswers(socket,id){
    if(id === 12){
      socket.emit('message', {
        code:'200',
        data: await getNewData()
      })
    } else {
      socket.emit('message', {
        code:'200',
        data: answers.answers.filter(item => item.questionIds.includes(id))
      })
    }
  }
}


const robotSocketCk = (io) => {
  io.on('connection',socket => {
      Object.keys(onEvents).forEach(eventName => {
        const ck = onEvents[eventName] || (() => {});
        socket.on(eventName, data => ck(socket, data));
      });
  })
}


module.exports = robotSocketCk;